const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const connectDB = require('./config/db');

// 加载环境变量
dotenv.config();

// 连接数据库
connectDB();

// 初始化Express应用
const app = express();

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));

// 基础路由
app.get('/api/health', (req, res) => {
  res.status(200).json({ status: 'success', message: 'API服务正常运行' });
});

// 导入路由
const userRoutes = require('./routes/userRoutes');
const siteRoutes = require('./routes/siteRoutes');
const keywordRoutes = require('./routes/keywordRoutes');
const auditRoutes = require('./routes/auditRoutes');
const competitorRoutes = require('./routes/competitorRoutes');

// 使用路由
app.use('/api/users', userRoutes);
app.use('/api/sites', siteRoutes);
app.use('/api/keywords', keywordRoutes);
app.use('/api/audits', auditRoutes);
app.use('/api/competitors', competitorRoutes);

// 生产环境下提供静态文件
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../../frontend/build')));

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../../frontend', 'build', 'index.html'));
  });
}

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    status: 'error',
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : {}
  });
});

// 设置端口并启动服务器
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`服务器在端口 ${PORT} 上运行中...`);
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err);
  process.exit(1);
});

// 处理未处理的Promise拒绝
process.on('unhandledRejection', (err) => {
  console.error('未处理的Promise拒绝:', err);
  process.exit(1);
});